package com.example.voiceassistant;

import com.example.voiceassistant.ai.AIResponseService;
import com.example.voiceassistant.asr.AsrStreamingEngine;
import com.example.voiceassistant.audio.AudioCaptureService;
import com.example.voiceassistant.audio.WakeWordDetector;
import com.example.voiceassistant.config.ConfigManager;
import com.example.voiceassistant.dialog.DialogSessionManager;
import com.example.voiceassistant.monitoring.MonitoringService;
import com.example.voiceassistant.tts.TtsEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 应用入口，用于拉起语音交互流程的常驻实现。
 */
public class App {

    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        ConfigManager configManager = new ConfigManager();
        MonitoringService monitoringService = new MonitoringService();

        AIResponseService aiResponseService = new AIResponseService(configManager, monitoringService);
        TtsEngine ttsEngine = new TtsEngine(configManager, monitoringService);
        AsrStreamingEngine asrStreamingEngine =
                new AsrStreamingEngine(configManager, monitoringService, aiResponseService);

        DialogSessionManager dialogSessionManager =
                new DialogSessionManager(configManager, monitoringService, asrStreamingEngine, ttsEngine);

        WakeWordDetector wakeWordDetector =
                new WakeWordDetector(configManager, monitoringService, dialogSessionManager);

        AudioCaptureService audioCaptureService = new AudioCaptureService(configManager, monitoringService);
        audioCaptureService.addListener(wakeWordDetector);
        audioCaptureService.addListener(dialogSessionManager);

        LOGGER.info("启动语音交互系统，常驻监听模式，按 Ctrl+C 停止。");

        // 添加优雅关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            LOGGER.info("接收到停止信号，准备优雅停机。");
            audioCaptureService.stop();
            dialogSessionManager.shutdown();
            asrStreamingEngine.shutdown();
            ttsEngine.shutdown();
            monitoringService.event("app.shutdown", "user_interrupt");
        }));

        audioCaptureService.start();

        // 主线程阻塞，常驻运行
        try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            LOGGER.info("主线程中断，准备停机。");
        }
    }
}

